package org.dreamwork.jasmine2.web.controls;

import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.peony.DataBinder;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-22
 * Time: 23:24:48
 */
public class Label extends WebControl {
    private String text;

    public void init () {
        htmlTagName = "label";
        super.init ();
    }

    public String getText () {
        return text;
    }

    public void setText (String text) {
        this.text = text;
        if (viewStateEnabled)
            stateManager.put ("text", text);
    }

    public void onDataBind (Object sender) throws EventException {
        if (dataSource != null || valueField != null) {
            Object value = DataBinder.eval (dataSource, valueField);
            setText (value == null ? "" : value.toString ());
        }
    }

    protected void loadViewState (Object savedState) throws IOException {
        stateManager.loadViewState (savedState);
        String text = (String) stateManager.get ("text");
        if (text != null)
            setText (text);
    }

    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        super.onPrerender (sender, context);
        attrs.remove ("value");
        attrs.remove ("id");
    }

    public void render (PrintWriter writer) throws IOException, EventException {
        writer.write ("<label");
        String clientId = getClientId ();
        if (clientId != null)
            writer.write (" id=\"" + clientId + "\"");

        super.renderAttributes (writer);
        writer.write (">");
        writer.print (text == null ? "" : text);
        writer.println ("</" + htmlTagName + ">");
    }
}